package com.itboye.textileexpres.base;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.textileexpres.R;
import com.itboye.textileexpres.util.LoadingDialog;

/**
 * 继承自该Fragment的类不需要findViewById，在onActivityCreated中调用super.onActivityCreated()
 * 后即可直接使用全局的控件了
 * 
 * @author Mr.w
 * 
 */
public abstract class BaseFragment extends Fragment {
	int states;
	LoadingDialog progressDialog = null;
	// private PushAgent mPushAgent;
	public static final String EVENT_TYPE_UNKNOWN = BaseActivity.class
			.getName() + "_unknown";

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// mPushAgent = PushAgent.getInstance(getActivity());
		// mPushAgent.enable();
		// mPushAgent.onAppStart();
		smartInject(getView());
		progressDialog = new LoadingDialog();
		onMyActivityCreated();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	protected void smartInject(View view) {
		try {
			Class<? extends Fragment> clz = getClass();
			while (clz != BaseFragment.class) {
				Field[] fs = clz.getDeclaredFields();
				Resources res = getResources();
				String packageName = getActivity().getPackageName();
				for (Field field : fs) {
					if (!View.class.isAssignableFrom(field.getType())) {
						continue;
					}
					int viewId = res.getIdentifier(field.getName(), "id",
							packageName);
					if (viewId == 0)
						continue;
					field.setAccessible(true);
					try {
						View v = view.findViewById(viewId);
						field.set(this, v);
						Class<?> c = field.getType();
						Method m = c.getMethod("setOnClickListener",
								android.view.View.OnClickListener.class);
						m.invoke(v, this);
					} catch (Throwable e) {
					}
					field.setAccessible(false);

				}

				clz = (Class<? extends Fragment>) clz.getSuperclass();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param data
	 * @return 2016-4-23 hebidu
	 */
	public ResultEntity handlerError(Object data) {
		ResultEntity result = (ResultEntity) data;
		if (result == null) {
			result = new ResultEntity("-1", "数据格式错误!~", data);
			return result;
		}

		if (result.hasError()) {

			if (result.getMsg().contains("java.net.UnknownHostException")) {
				toast("请连接网络 ");
			} else {
				toast(result.getMsg());
			}
			result.setEventType(EVENT_TYPE_UNKNOWN);
			return result;
		}

		return result;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(initView(), null);
	}

	public abstract int initView();

	public abstract void onMyActivityCreated();

	/**
	 * 显示进度对话框,带有消息 flag 是否可以取消
	 */
	@SuppressLint("NewApi")
	public void showProgressDialog(String message, boolean flag) {
		if (progressDialog == null)
			return;
		setProgressDialogMessage(message);
		progressDialog.show(getActivity().getFragmentManager(), message);
		progressDialog.setCancelable(flag);

	}

	/**
	 * 设置进度对话框消息
	 * 
	 * @param message
	 */
	public void setProgressDialogMessage(String message) {
		progressDialog.setMsg(message);
	}

	/**
	 * 关闭进度对话框
	 */
	@SuppressLint("NewApi")
	public void closeProgressDialog() {
		if (progressDialog != null) {
			if (progressDialog.getDialog().isShowing()) {
				progressDialog.dismiss();
			}
		}
	}

	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return false;
	}

	public void showMyToast(final Toast toast, final int cnt) {
		final Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				toast.show();
			}
		}, 0, 3000);
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				toast.cancel();
				timer.cancel();
			}
		}, cnt);
	}

	public void toast(String text) {
		LayoutInflater inflater = getActivity().getLayoutInflater();
		View view = inflater.inflate(R.layout.toast, null);
		TextView textView = (TextView) view.findViewById(R.id.toast_tv);
		textView.setText(text);
		Toast toast = new Toast(MainApplication.getContext());
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(view);
		showMyToast(toast, 1000);
	}

	public int ChangeToDP(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	public static String getAppVersionName(Context context) {
		String versionName = "";
		String vsersionNmae = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;

			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			Log.e("VersionInfo", "Exception", e);
		}
		return versionName;
	}

}
